import router, { constantRoutes, otherRoutes } from '@/router'
import RegionSelect from 'region-select'
import Vue from 'vue'
import { isEmpty } from '@/utils'

const state = {
  routes: [],
  dynamicRoutes: [],
  pageButtonList: {},
  dict: {},
  areaTree: [],
  allAreaTree: [],
  gaodeDict: [],
  isLogin: false
}

const mutations = {
  SET_ROUTES: (state, value) => {
    state.dynamicRoutes = value
    state.routes = constantRoutes.concat(value).concat(otherRoutes)
  },
  SET_AUTH_BUTTONS: (state, value) => {
    state.pageButtonList = value
  },
  SET_DICT: (state, value) => {
    state.dict = value
    Vue.prototype.$dict = value
  },
  SET_AREA_TREE: (state, value) => {
    state.areaTree = value
  },
  SET_ALL_AREA_TREE: (state, value) => {
    state.allAreaTree = value
  },
  SET_GAODEDICT: (state, value) => {
    state.gaodeDict = value
  },
  SET_IS_LOGIN: (state, value) => {
    state.isLogin = value
  }
}

const actions = {
  getDynamicRoutes ({ commit, state }, roles) {
    return new Promise(resolve => {
      Vue.prototype.$POST('sot-admin-api/sys/queryMenuList').then(res => {
        let dynamicRoutes = [],
          authButtons = []
        if (!isEmpty(res.data)) {
          dynamicRoutes = filterAsyncRoutes(res.data, router)
          authButtons = genAuthButtons(dynamicRoutes)
          commit('SET_ROUTES', dynamicRoutes)
          commit('SET_AUTH_BUTTONS', authButtons)
          commit('SET_IS_LOGIN', true) // 记录是否已经成功登录
        }
        let routers = dynamicRoutes.concat(otherRoutes)
        routers.forEach(item => {
          router.addRoute(item)
        })

        resolve(dynamicRoutes)
      })

      // 【数据字典】根据项目需要修改
      Vue.prototype.$GET('sot-admin-api/sys/getDomainDataDict').then(res => {
        if (res.data) {
          commit('SET_DICT', res.data)
        }
      })

      // 全局地区树
      actions.getAllArea({ commit, state })

      // 获取项目设置的区域树
      Vue.prototype
        .$POST('sot-admin-api/sys/areaSelect/listAllSelectArea', {})
        .then(res => {
          if (res.data) {
            // 注册地区选择组件
            Vue.use(RegionSelect, {
              data: res.data.map(item => ({
                value: item.code,
                label: item.name
              }))
            })
            commit('SET_AREA_TREE', res.data || [])
          }
        })

      // 获取高德字典表
      Vue.prototype
        .$GET('one-travel-api/getPoiTreeByCode?dictCode')
        .then(res => {
          if (res.data) {
            commit('SET_GAODEDICT', res.data)
          } else {
            err('获取高德数据字典失败')
          }
        })

      // 【用户信息】根据项目需要修改
      /*Vue.prototype.$POST('auth/getUserInfoByUserId').then(res => {
        if (res.data) {
          commit('user/SET_USER_INFO', res.data, { root: true })
        }
      })*/
    })
  },
  getAllArea ({ commit, state }) {
    // 全局地区树
    return Vue.prototype
      .$POST('sot-admin-api/sys/area/getAreaTree', {
        code: '000000000000',
        level: 3
      })
      .then(res => {
        if (res.data.length > 0) {
          let areaTree = []
          commit('SET_ALL_AREA_TREE', res.data[0]?.children || [])
        }
      })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

const menuContainer = [
  () => import('@/layout'),
  () => import('@/layout/twoLevelLayout.vue'),
  () => import('@/layout/twoLevelLayout.vue')
]

export function filterAsyncRoutes (routes) {
  let viewsPath = []
  viewsPath = import.meta.glob('@/views/**/*.vue') // vite动态引入文件

  function replaceComponent (routes, parentPath = '', level = 0) {
    routes.map(item => {
      if (item.path && !item.path.startsWith('/')) {
        item.path = '/' + item.path // 补全根路径
      }

      if (item.type === '0' && !item.children) {
        return // 去掉空目录
      }

      // 目录
      if (item.type === '0') {
        item.component = menuContainer[level] // 目录容器
      }
      // 菜单
      if (item.type === '1') {
        const secondLevelMenu = parentPath + item.path
        try {
          item.component = viewsPath[`/src/views${secondLevelMenu}.vue`]
          // item.component = resolve =>
          //   require([`@/views${secondLevelMenu}`], resolve)
          // 绑定页面自定义配置
          if (item.configure) {
            item.meta.configure = JSON.parse(item.configure)
          }
        } catch (e) {
          console.error('在引入该页面时出错：' + secondLevelMenu)
          console.log(e)
        }
      }

      if (item.children) {
        const children = replaceComponent(
          item.children,
          parentPath + item.path,
          1 + level
        )
        // 访问根路径时定向到第一个界面
        item.children = [
          {
            path: '/',
            redirect: parentPath + item.path + `/${children[0].path}`
          },
          ...children
        ]
      } else {
        item.children = []
      }

      if (level != 0) {
        // 除了根目录，vue-router 其他子目录不需要 /
        item.path = item.path.substring(1)
      }
      return item
    })

    return routes
  }

  replaceComponent(routes)

  // 如果静态菜单中已经存在根目录 则不生成
  const isRoot = router.options.routes.some(_ => _.path === '/')
  if (!isRoot) {
    // 没有根目录的话，重定向到第一个界面
    routes.unshift({
      path: '/',
      redirect: routes[0].path
    })
  }

  return routes
}

function genAuthButtons (routes) {
  const pageButtonList = {}
  function replaceComponent (routes, parentPath = '') {
    for (const v of routes) {
      let keyPath = v.path
      if (v.path && !v.path.startsWith('/')) {
        keyPath = '/' + v.path // 补全根路径
      }
      if (v.type === '1') {
        const key = parentPath + keyPath
        pageButtonList[key] = []
        if (v.hasPermission === 1 && v.pageButtonList) {
          pageButtonList[key] = v.pageButtonList.map(v => v.name)
        }
      }
      if (v.children && v.children.length > 0) {
        replaceComponent(v.children, parentPath + keyPath)
      }
    }
  }

  if (!isEmpty(routes)) {
    replaceComponent(routes)
  }

  return pageButtonList
}
